<?php
use Think\Db\Driver;

/**
 * 扩展自TP的hive操作类
 * Class Hive
 *
 * $hive = new Hive();
 * $hive->connect('127.0.0.1', '8888','hive', 'default');
 * var_dump($hive->table('table_hive')->field('count(1) as num')->where('1=1')->select());
 */
class Hive extends Driver
{

    private $presto;
    private $table;
    private $fields;
    private $where;
    private $limit = '';
    private $group = '';
    private $order = '';

    public function __construct($config = '')
    {
        parent::__construct($config);
    }

    public function connect($ip, $port, $catalog = 'hive', $schema = 'default')
    {
        require_once 'PrestoClient.php';
        $this->presto = new \PrestoClient($ip, $port, $catalog, $schema);
    }

    public function querySql($sql)
    {
        try {
//            echo $sql;
            $this->presto->Query($sql);
        } catch (\Exception $e) {
            return false;
        }
        $this->presto->WaitQueryExec();
        return $this->presto->GetData();
    }

    public function select()
    {
        return $this->querySql('select '.$this->fields.' from '.$this->table.' '.
            $this->parseWhere(!empty($this->where) ? $this->where : '') .
            ($this->group == '' ? '' : ' group by '.$this->group).
            ($this->order == '' ? '' : ' order by '.$this->order).
            ($this->limit == '' ? '' : ' limit '.$this->limit));
    }

    public function table($tableName)
    {
        $this->table = $tableName;
        return $this;
    }

    /**
     * @param array|string $where
     * @return $this
     */
    public function where($where)
    {
        $this->where = $where;
        return $this;
    }

    /**
     * @param string|array $fields
     * @return Hive
     */
    public function field($fields = '*')
    {
        if (is_array($fields)) {
            $this->fields = implode(',', $fields);
        } else {
            $this->fields = $fields;
        }
        return $this;
    }

    /**
     * 指定查询数量
     * @access public
     * @param mixed $offset 起始位置
     * @param mixed $length 查询数量
     * @return Hive
     */
    public function limit($offset, $length = null)
    {
        if (is_null($length) && strpos($offset, ',')) {
            list($offset, $length) = explode(',', $offset);
        }
        $this->limit = intval($offset) . ($length ? ',' . intval($length) : '');
        return $this;
    }

    public function order($order){
        $this->order = $order;
        return $this;
    }

    public function group($group){
        $this->group = $group;
        return $this;
    }
}